<template>
  <div class="product-management-container">
    <div class="page-header">
      <h1>商品管理</h1>
      <div class="header-actions">
        <div class="search-area">
          <el-input
            v-model="searchQuery"
            placeholder="输入商品名称搜索"
            prefix-icon="Search"
            :style="{ width: '240px' }"
            @keyup.enter="handleSearch"
          />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="clearSearch">清空</el-button>
        </div>
      </div>
    </div>

    <div class="table-container">
      <div class="action-buttons">
        <el-button type="primary" icon="Plus" @click="handleAddProduct">
          添加商品
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="productsList"
        :default-sort="{ prop: 'id', order: 'ascending' }"
      >
        <!-- 添加序号列 -->
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="name"
          label="商品名称"
          width="200"
          align="center"
        />
        <el-table-column prop="price" label="价格" width="120" align="center">
          <template #default="scope">
            {{ "¥" + scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200">
          <template #default="scope">
            <div class="description-cell" :title="scope.row.description || ''">
              {{ scope.row.description || "-" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="created_at"
          label="创建时间"
          width="180"
          align="center"
        >
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="updated_at"
          label="更新时间"
          width="180"
          align="center"
        >
          <template #default="scope">
            {{ formatDate(scope.row.updated_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        size="small"
        background
        layout="sizes, prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加商品弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加商品"
      width="500px"
      :before-close="handleClose"
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="80px"
        class="product-form"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input
            v-model="productForm.price"
            type="number"
            placeholder="请输入商品价格"
            min="0"
            step="0.01"
          />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="productForm.description"
            type="textarea"
            placeholder="请输入商品描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            action=""
            :show-file-list="true"
            :on-change="handleImageChange"
            :auto-upload="false"
            :before-upload="beforeUpload"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑商品弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑商品"
      width="500px"
      :before-close="handleEditClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
        class="product-form"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input
            v-model="editForm.price"
            type="number"
            placeholder="请输入商品价格"
            min="0"
            step="0.01"
          />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            placeholder="请输入商品描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <el-upload
            ref="editUploadRef"
            class="avatar-uploader"
            action=""
            :show-file-list="true"
            :on-change="handleEditImageChange"
            :auto-upload="false"
            :before-upload="beforeUpload"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
            </template>
          </el-upload>
        </el-form-item>
        <!-- 将图片显示移到表单最后，并添加标题 -->
        <div v-if="editForm.image">
          <div style="margin-bottom: 10px; font-weight: bold">当前图片</div>
          <el-image
            :key="editForm.imagePreviewKey || 'default'"
            :src="getImageUrl(editForm.image)"
            alt="当前商品图片"
            :preview-src-list="[getImageUrl(editForm.image)]"
            :style="{ width: '100px', height: '100px' }"
            fit="cover"
          />
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleEditClose">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
// 导入添加商品的API函数
import {
  getProductsList as fetchProductsList,
  addProduct,
  updateProduct,
  deleteProduct,
} from "../../api/product.js";

// 商品列表相关状态
const productsList = ref([]);
const currentPage = ref(1);
const total = ref(0);
const pageSize = ref(10);
const searchQuery = ref("");
const loading = ref(false);

// 添加商品相关状态
const dialogVisible = ref(false);
const productFormRef = ref(null);
const uploadRef = ref(null);
const editUploadRef = ref(null);
const productForm = ref({
  name: "",
  price: 0,
  description: "",
  image: null,
});
const productRules = ref({
  name: [
    { required: true, message: "请输入商品名称", trigger: "blur" },
    {
      min: 2,
      max: 100,
      message: "商品名称长度在 2 到 100 个字符之间",
      trigger: "blur",
    },
  ],
});

// 编辑商品相关状态
const editDialogVisible = ref(false);
const editFormRef = ref(null);
const editForm = ref({
  id: "",
  name: "",
  price: 0,
  description: "",
  image: null,
});
const editRules = ref({
  name: [
    { required: true, message: "请输入商品名称", trigger: "blur" },
    {
      min: 2,
      max: 100,
      message: "商品名称长度在 2 到 100 个字符之间",
      trigger: "blur",
    },
  ],
  price: [
    { required: true, message: "请输入商品价格", trigger: "blur" },
    { type: "number", min: 0.01, message: "价格必须大于0", trigger: "blur" },
  ],
});

// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return "-";
  return dayjs(dateString).format("YYYY-MM-DD HH:mm:ss");
};

// 文件上传前的校验
const beforeUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
};

// 处理图片选择
const handleImageChange = (file, fileList) => {
  productForm.value.image = file.raw;
};

// 处理编辑时的图片选择
const handleEditImageChange = (file, fileList) => {
  editForm.value.image = file.raw;
  editForm.value.imagePreviewKey = Date.now();
};

//获取商品列表
const getProductsData = async () => {
  try {
    // 设置加载状态为true
    loading.value = true;
    // 调用API函数时传递所有必要参数
    const response = await fetchProductsList(
      currentPage.value,
      pageSize.value,
      searchQuery.value.trim()
    );

    // 更新商品列表数据和总条数
    productsList.value = response.results || [];
    total.value = response.count || 0;

    // 如果当前页没有数据且不是第一页，则返回上一页
    if (productsList.value.length === 0 && currentPage.value > 1) {
      currentPage.value--;
      await getProductsData();
    }
  } catch (error) {
    // 错误处理
    console.error("获取商品列表失败:", error);
    ElMessage.error(`获取商品列表失败：${error.message || "未知错误"}`);

    // 重置商品列表数据
    productsList.value = [];
    total.value = 0;
  } finally {
    // 设置加载状态为false
    loading.value = false;
  }
};

// 页码变化处理
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getProductsData();
};

// 每页条数变化处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置为第一页
  getProductsData();
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1; // 重置为第一页
  getProductsData(); // 修改为getProductsData
};

// 清空搜索
const clearSearch = () => {
  searchQuery.value = "";
  currentPage.value = 1; // 重置为第一页
  getProductsData(); // 修改为getProductsData
};
// 添加商品处理函数
const handleAddProduct = () => {
  dialogVisible.value = true;
};
// 提交添加商品
const handleSubmit = async () => {
  try {
    // 手动触发表单验证
    await productFormRef.value.validate();
    // 显示加载状态
    loading.value = true;
    // 调用添加商品API
    const result = await addProduct({
      name: productForm.value.name,
      price: productForm.value.price,
      description: productForm.value.description,
      image: productForm.value.image,
    });
    // 显示成功消息
    ElMessage.success("商品添加成功！");
    // 关闭弹窗
    dialogVisible.value = false;
    // 重置表单
    resetProductForm();
    // 重新加载商品列表
    getProductsData();
  } catch (error) {
    // 改进错误处理，从error对象中提取更详细的错误信息
    console.error("提交商品失败:", error);
    let errorMessage = "未知错误";
    if (error.response && error.response.data) {
      if (error.response.data.message) {
        errorMessage = error.response.data.message;
      } else if (typeof error.response.data === "string") {
        errorMessage = error.response.data;
      } else {
        // 尝试获取所有字段的错误信息
        const errorMessages = [];
        for (const [field, msgs] of Object.entries(error.response.data)) {
          if (Array.isArray(msgs)) {
            errorMessages.push(...msgs);
          } else {
            errorMessages.push(`${field}: ${msgs}`);
          }
        }
        if (errorMessages.length > 0) {
          errorMessage = errorMessages.join("，");
        }
      }
    } else if (error.message) {
      errorMessage = error.message;
    }
    ElMessage.error(`添加商品失败：${errorMessage}`);
  } finally {
    // 隐藏加载状态
    loading.value = false;
  }
};

// 重置商品表单
const resetProductForm = () => {
  // 先清除上传组件的文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
  productForm.value = {
    name: "",
    price: 0,
    description: "",
    image: null,
  };

  if (productFormRef.value) {
    productFormRef.value.resetFields();
  }
};

const handleClose = () => {
  // 关闭添加弹窗
  dialogVisible.value = false;
  // 重置表单
  setTimeout(() => {
    resetProductForm();
  }, 300);
};

const getImageUrl = (imageData) => {
  if (!imageData) return "";

  // 如果是File对象，创建临时URL用于预览
  if (imageData instanceof File) {
    return URL.createObjectURL(imageData);
  }
  // 如果图片路径已经是完整URL，则直接返回
  if (typeof imageData === "string" && imageData.startsWith("http")) {
    return imageData;
  }
  // 否则，拼接基础URL
  return `http://127.0.0.1:8000${imageData}`;
};

// 编辑商品处理函数
const handleEdit = (row) => {
  // 打开编辑弹窗
  editDialogVisible.value = true;
  // 填充编辑表单数据
  editForm.value = {
    id: row.id,
    name: row.name,
    price: parseFloat(row.price),
    description: row.description || "",
    image: row.image || null, // 保存原始图片路径
    originalImage: row.image || null, // 保存原始图片路径的副本，用于重置
  };
  // 重置表单验证状态
  if (editFormRef.value) {
    editFormRef.value.clearValidate();
  }
};

// 重置编辑表单
const resetEditForm = () => {
  // 清除上传组件的文件列表
  if (editUploadRef.value) {
    editUploadRef.value.clearFiles();
  }
  // 重置表单数据
  editForm.value = {
    id: "",
    name: "",
    price: 0,
    description: "",
    image: null,
    originalImage: null,
  };
  // 重置表单验证状态
  if (editFormRef.value) {
    editFormRef.value.resetFields();
  }
};

// 关闭编辑弹窗
const handleEditClose = () => {
  // 关闭弹窗
  editDialogVisible.value = false;
  // 重置表单
  setTimeout(() => {
    resetEditForm();
  }, 300);
};

// 提交编辑商品
const handleEditSubmit = async () => {
  try {
    // 手动触发表单验证
    await editFormRef.value.validate();
    // 显示加载状态
    loading.value = true;
    // 调用更新商品API
    const result = await updateProduct(editForm.value.id, {
      name: editForm.value.name,
      price: editForm.value.price,
      description: editForm.value.description,
      image: editForm.value.image,
    });
    // 显示成功消息
    ElMessage.success("商品更新成功！");
    // 关闭弹窗
    editDialogVisible.value = false;
    // 重置表单
    resetEditForm();
    // 重新加载商品列表
    getProductsData();
  } catch (error) {
    // 错误处理
    console.error("更新商品失败:", error);
    let errorMessage = "未知错误";
    if (error.response && error.response.data) {
      if (error.response.data.message) {
        errorMessage = error.response.data.message;
      } else if (typeof error.response.data === "string") {
        errorMessage = error.response.data;
      } else {
        // 尝试获取所有字段的错误信息
        const errorMessages = [];
        for (const [field, msgs] of Object.entries(error.response.data)) {
          if (Array.isArray(msgs)) {
            errorMessages.push(...msgs);
          } else {
            errorMessages.push(`${field}: ${msgs}`);
          }
        }
        if (errorMessages.length > 0) {
          errorMessage = errorMessages.join("，");
        }
      }
    } else if (error.message) {
      errorMessage = error.message;
    }
    ElMessage.error(`更新商品失败：${errorMessage}`);
  } finally {
    // 隐藏加载状态
    loading.value = false;
  }
};

// 删除商品处理
const handleDelete = async (row) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要删除商品 "${row.name}" 吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    // 显示加载状态
    loading.value = true;
    // 调用删除商品API
    await deleteProduct(row.id);
    // 显示成功消息
    ElMessage.success("商品删除成功！");
    // 重新加载商品列表
    getProductsData();
  } catch (error) {
    // 错误处理或用户取消操作
    if (error === "cancel") {
      return;
    }
    console.error("删除商品失败:", error);
    ElMessage.error(`删除商品失败：${error.message || "未知错误"}`);
  } finally {
    // 隐藏加载状态
    loading.value = false;
  }
};

onMounted(() => {
  getProductsData();
});
</script>

<style lang="less" scoped>
.product-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeef3;
}

.header-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.search-area {
  display: flex;
  gap: 10px;
}

.table-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  padding-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

// 描述列样式，限制显示行数并添加省略号
.description-cell {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

// 修复固定列导致的表格不完整问题
::v-deep .el-table {
  width: 100% !important;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

// 确保表格容器与内容正确对齐
::v-deep .el-table__body-wrapper {
  width: 100% !important;
}

::v-deep .el-table th,
::v-deep .el-table td {
  text-align: center !important;
}
</style>
